/**
 * Created by lixiaodi on 2019/06/28 0026.
 * 公告/周例会/新闻管理
 */

mini.parse();
var grid = mini.get('datagrid1');
var initParam = '';
var noticeType = '';				//文章类型
var articleTitle = '';				//新增文章时标题
var pager = grid.getBottomPager();
var searchForm = new mini.Form("searchFormBar");	//搜索栏目

//根据条件查询
function onSearch(){
	//得到查询条件数据
	searchData = searchForm.getData();
	//拼接查询sql
	var dataStr = "";       //存放sql
    for(var key in searchData){
    	if(searchData[key]){
    		if(key == 'book_isbn'){
    			dataStr += " and "  + key + " in (" + searchData[key] + ")";
    		}else{
    			dataStr += " and "  + key + " like '%" + searchData[key] + "%'";
    		}
    	}
    }
    var searchSql = dataStr;
	//查询数据
	httpRequest('0',searchSql);
}


//表格的操作按钮绘制
function onActionRenderer(e) {
    var grid = e.sender;
    var record = e.record;
    var uid = record._uid;
    var rowIndex = e.rowIndex;
    var s = ' <a class="mini-button Edit_Button" href="javascript:onSee(\'' + uid + '\')" >查看</a>'
    		+ ' <a class="mini-button Edit_Button" href="javascript:onEdit(\'' + uid + '\')" >编辑</a>'
    		+ ' <a class="mini-button Edit_Button" href="javascript:onRemove(\'' + uid + '\')" >删除</a>';
    return s;
}	
//页面初始化
$(function(){
	//获取当前选项卡
	console.log(parent.tabsEl)
	var tab = parent.tabsEl.getActiveTab();
	switch (tab.title){
		case '公告管理01':
			noticeType = 1;
			articleTitle = '公告';
			break;
		case '周例会管理':
			noticeType = 3;
			articleTitle = '周例会';
			break;
		case '新闻管理':
			noticeType = 2;
			articleTitle = '新闻';
			break;
	}
	httpRequest();
});

//新增
function onAdd(){
	//先清除缓存
	var localCon = localStorage.getItem("newNotice");
	if(localCon){
		//清除缓存
		localStorage.removeItem('newNotice');
	}
	//判断新增文章页面是否打开
	var allOpenTabs = parent.openTabs();
	console.log(parent.openTabs)
	//如果有新增页面就关闭
	allOpenTabs.forEach(function (item,index){
		if(item.title.substr(0,2) == '新增'){
			parent.articleTab(item);
		}
	});
	//跳转新增页签
	var noticeData = {
		types: 'new',
		pageTitle: articleTitle
	}
	//将需要编辑的数据带过去
	localStorage.setItem("newNotice",JSON.stringify(noticeData));
	var jumpUrl = "../pages/booking/noticeManagement/notifiAdd.html";
	onJump('新增'+articleTitle,jumpUrl);
}

//编辑
function onEdit(row_uid){
	//得到需要编辑的文章
	var row = grid.getRowByUID(row_uid);
	if(row){
		//先得到缓存并清除缓存
		var localCon = localStorage.getItem("newNotice");
		if(localCon){
			//清除缓存
			localStorage.removeItem('newNotice');
		}
		//判断编辑文章页面是否打开
		var allOpenTabs = parent.openTabs();
		//如果有编辑页面就关闭
		allOpenTabs.forEach(function (item,index){
			if(item.title.substr(0,2) == '编辑'){
				parent.articleTab(item);
			}
		});
		//跳转新增页签
		var noticeData = {
			types: 'edit',
			pageTitle: articleTitle,
			articleData: row
		}
		//将需要编辑的数据带过去
		localStorage.setItem("newNotice",JSON.stringify(noticeData));
		var jumpUrl = "../pages/booking/weeklynotice/notifiAdd.html";
		onJump('编辑'+articleTitle,jumpUrl);
	}else{
		mini.alert('请选择一条编辑');
	}
}
//查看
function onSee(row_uid){
	//得到需要编辑的文章
	var row = grid.getRowByUID(row_uid);
	if(row){
		//先得到缓存并清除缓存
		var localCon = localStorage.getItem("seeArticle");
		if(localCon){
			//清除缓存
			localStorage.removeItem('seeArticle');
		}
		//判断文章正文页面是否打开
		var allOpenTabs = parent.openTabs();
		//如果有新增页面就关闭
		allOpenTabs.forEach(function (item,index){
			var len = item.title.length;
			if(item.title.substr(len-2,2) == '正文'){
				parent.articleTab(item);
			}
		});
		//跳转新增页签
		var noticeData = {
			types: 'see',
			articleData: row
		}
		//将需要编辑的数据带过去
		localStorage.setItem("seeArticle",JSON.stringify(noticeData));
		var jumpUrl = "../pages/booking/weeklynotice/article.html";
		onJump(articleTitle + '正文',jumpUrl);
	}else{
		mini.alert('请选择一条查看');
	}
}
//删除(单条删除)
function onRemove(row_uid){
	var row = grid.getRowByUID(row_uid);
	//判断是否发布，发布以后不允许删除
	if(row.publisher_state == '未发布'){
		mini.confirm('是否删除选中记录','系统提示',function (action){
			if(action == 'ok'){
				$.ajax({
					url: ajaxUrl + '/delete.do?ids=' + row.notice_id,
					type: "post",
					success: function (data) {
						if(data.status == '200'){
							showTips2(data.message);
						}else{
							mini.alert(data.statusName);
						}
						httpRequest();
					},
					error: function () {
						mini.alert('失败');
					}
				});
			}
		});
	}else{
		mini.alert('已发布不允许删除，如需删除请先撤销再删除');
	}
}
//删除（多条）
function onRemoves(){
	var rows = grid.getSelecteds();
	if(rows.length > 0){
		var releaseArr = [];			//已发布
		var unReleaseArr = [];			//未发布
		//遍历选中的行，判断每条数据状态是否为已发布，如果是已发布则不允许删除
		rows.forEach(function(item){
			if(item.publisher_state == '已发布'){
				releaseArr.push(item);
			}else{
				unReleaseArr.push(item);
			}
		});
		//如果选择的有未发布的，那么删除,否则提示无可删除的信息
		if(unReleaseArr.length > 0){
			mini.confirm('是否删除选中记录','系统提示',function (action){
				if(action == 'ok'){
					var ids = [];
					for(var i = 0; i < unReleaseArr.length; i++){
						var r = rows[i];
						ids.push(r.notice_id);
					}
					var id = ids.join(',');
					console.log(id)
					$.ajax({
						url: ajaxUrl + '/deleteMore.do',
						type: "post",
						data:{
							ids : id
						},
						success: function (data) {
							if(data.status == 200){
								showTips2(data.message);
								httpRequest();
							}else{
								mini.alert(data.statusName);
							}

						},
						error: function () {
							mini.alert('失败');
						}
					});
				}
			});
		}else{
			mini.alert('已发布的不可删除');
		}

	}else{
		mini.alert('请选择要删除的项');
	}
}
//发布
function onRelease(){
	var rows = grid.getSelecteds();
	if(rows.length == 1){
		mini.confirm('是否发布选中记录','系统提示',function (action){
			if(action == 'ok'){
				$.ajax({
	             	url: ajaxUrl + '/publishNotice.do?state=1&param='+rows[0].notice_id,
	                 type: "post",
	                 success: function (data) {
	                	 if(data.status == 200){
	                		showTips2(data.message);
	 	                 	httpRequest();
	                	 }else{
	                		 mini.alert(data.statusName);
	                	 }
	                 },
	                 error: function () {
	                     mini.alert('失败');
	                 }
	            });
			}
		});
	}else{
		mini.alert('请选择一条要发布的项');
	}
}
//撤销
function onOut(){
	var rows = grid.getSelecteds();
	if(rows.length == 1){
		mini.confirm('是否发布选中记录','系统提示',function (action){
			if(action == 'ok'){
				$.ajax({
					url: ajaxUrl + '/publishNotice.do?state=0&param='+rows[0].notice_id,
					type: "post",
					success: function (data) {
						if(data.status == 200){
							showTips2(data.message);
							httpRequest();
						}else{
							mini.alert(data.statusName);
						}
					},
					error: function () {
						mini.alert('失败');
					}
				});
			}
		});
	}else{
		mini.alert('请选择一条要撤销的项');
	}
}
//跳转函数
function onJump(text,jumpUrl){
	//跳转
	var item = {
		id: 'notice',
	    iconCls: "fa fa-desktop",
	    text: text,
	    url: jumpUrl
	};
	//var data = parent.allTabs();
	parent.activeTab(item);//与父页面通信
}
//list
function httpRequest(pageIndex,paramSql){
	var pageObj = {
			noticeType : noticeType,
			pageSize: '500',
			pageNum: pageIndex,
			paramSql: paramSql
	}
	var pageStr = JSON.stringify(pageObj);
	grid.loading('请稍后...');
	$.ajax({
		url: ajaxUrl + '/findAll.do',
		type: 'POST',
		data: pageStr,
		contentType : "application/json",
		success: function(data){
			console.log(data)
			grid.unmask();
			if(data.status == '706'){
				showTips('公告');
				grid.setData([]);
			}else if(data.status == '200'){
				var noticeList = data.data;
				noticeList.forEach((item)=>{
					item.publisher_state = item.publisher_state == '1' ? '已发布' : '未发布';
						if(item.creat_date){
							item.creat_date = formatDateSec(item.creat_date);
						}else{
							item.creat_date = '';
						}
						if(item.publisher_date){
							item.publisher_date = formatDateSec(item.publisher_date);
						}else{
							item.publisher_date = '';
						}
				});
				grid.setData(noticeList);
				pager.set({"totalCount":data.countData}); 
			}else{
				mini.alert(data.message);
			}
			
		},
		error: function(msg){
			console.log(msg);
			mini.alert('请求失败');
		}
	});
}
//提示信息
function showTips2(text) {
    mini.showTips({
        content: "<b>" + text + "</b>",
        state: "success",
        x: "center",
        y: "center",
        timeout: 2000
    });
}